const moment = require('moment');
const nodemailer = require('nodemailer');
const mailSender = nodemailer.createTransport({
  host: 'smtp.qq.com',
  port: 465,
  secure: true, // true for 465, false for other ports
  auth: {
    user: 'vector3@qq.com',
    pass: 'orxmmrrpayxvecfh'
  }
});
// const emails = ['1139051333@qq.com', 'gzlock88@gmail.com', '741374710@qq.com', '136764101@qq.com'];
const emails = ['1139051333@qq.com', 'gzlock88@gmail.com'];

/**
 * 发送警告邮件
 */

module.exports = {
  schedule: {
    immediate: true,
    interval: 60 * 1000, // 每分钟
    type: 'worker', // 指定 单一 worker 执行
    env: ['prod', 'unittest'],
  },
  async task(ctx) {
    const now = moment();
    let status = await ctx.app.redis.get('note:spider_mission_status');
    if (!status)
      return;
    status = JSON.parse(status);
    const lastTime = moment(status.lastTime);

    const minutes = now.diff(lastTime, 'minutes');

    //每次大于6分钟就发警告邮件
    if (status.lastTime > 0 && minutes > 6) {

      //重启所有爬虫
      const vps = await ctx.model.Vps.findAll({where: {status: 4}});

      if(vps.length === 0)
        return;

      vps.forEach(vps => {
        ctx.service.vps.execute(vps);
      });

      //更新redis记录
      status.lastTime = 0;
      await ctx.app.redis.set('note:spider_mission_status', JSON.stringify(status, null, 4));

      await new Promise(resolve => {
        mailSender.sendMail({
          from: '"爬虫系统发出警告" <vector3@qq.com>',
          bcc: emails.join(', '),
          subject: `系统爬虫任务超时 ${minutes} 分钟，已经自动重启`,
          text: `已经超时 ${minutes} 分钟，请前往总控(https://spider.beijingzhuyou.com)重启爬虫`,
          html: `<h2>已经超时 ${minutes} 分钟，已经自动重启全部爬虫，请前往 <a href="https://spider.beijingzhuyou.com">总控</a> 观察情况</h2>`,
        }, err => {
          if (err) console.log(err);
          resolve();
        });
      });
    }
  },
};